//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/exception/dao_exception.dart';
import 'package:hktk_app/ienum/home/column_type_enum.dart';
import 'package:hktk_app/ienum/subject/collection_type_enum.dart';
import 'package:hktk_app/model/home/column_model.dart';
import 'package:hktk_app/model/my/note_chapter_model.dart';
import 'package:hktk_app/model/page/resource_page_model.dart';
import 'package:hktk_app/util/data_util.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/toast_util.dart';
import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/mine/note_expandable_widget.dart';

/// 可展开页面，我的笔记章节/试卷
class NoteExpandablePage extends StatefulWidget {
  /// 栏目内容
  final ColumnModel tabModel;

  const NoteExpandablePage({
    super.key,
    required this.tabModel,
  });

  @override
  State<NoteExpandablePage> createState() => _NoteExpandablePageState();
}

class _NoteExpandablePageState extends State<NoteExpandablePage> {
  late BuildContext _context;

  /// 初始化方法
  late Future<Map<String, dynamic>> _futureInit;

  /// 相关数据
  late List<NoteChapterModel> _list;

  @override
  void initState() {
    super.initState();
    debugPrint("noteExpandablePage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _list = [];
    _futureInit = _initData();
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("noteExpandablePage 页面 -> dispose 方法执行 ===> ");
    debugPrint("");
    ToastUtil.loadingBoxRemove();
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("noteExpandablePage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return FutureBuilder<Map<String, dynamic>>(
      future: _futureInit,
      builder:
          (BuildContext context, AsyncSnapshot<Map<String, dynamic>> snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> map = snapshot.data!;
          if (!map["suc"]) {
            WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
              ToastUtil.show(context: _context, msg: map["msg"]);
            });
          }
          return _content();
        } else {
          return const Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

  /// 获取对应的类型
  CollectionTypeEnum _getType(ColumnTypeEnum type) {
    if (type == ColumnTypeEnum.paperLibrary) {
      return CollectionTypeEnum.paper;
    } else if (type == ColumnTypeEnum.chapterPractice) {
      return CollectionTypeEnum.chapter;
    }
    return CollectionTypeEnum.rankError;
  }

  /// 加载数据方法
  Future<Map<String, dynamic>> _initData() async {
    Map<String, dynamic> map = {};
    try {
      ResourcePageModel<NoteChapterModel> page = await MyDao.myNote(
        current: 1,
        size: 10,
        categoryId: dataUtilComm.dataModel.categoryId,
        newFlag: false,
        type: _getType(widget.tabModel.type!),
      );
      if (page.records != null) {
        _list = page.records!;
      }

      map["suc"] = true;
    } catch (e) {
      debugPrint("noteExpandablePage 页面 -> _initData 发生异常 ===> $e");
      map = {"suc": false, "msg": "未知错误，请重试"};
      if (e is DaoException) {
        debugPrint("noteExpandablePage 页面 -> dao异常 ===> ${e.msg}");
        map["msg"] = e.msg;
      }
    }
    return map;
  }

  /// 内容显示方法
  Widget _content() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 24),
      padding: EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: colorWhite1,
        borderRadius: BorderRadius.circular(20),
      ),
      child: _showConItem(),
    );
  }

  /// 数据显示
  _showConItem() {
    if (_list.isNotEmpty) {
      return MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView.builder(
          itemBuilder: _itemBuilder,
          itemCount: _list.length,
        ),
      );
    } else {
      return Center(
        child: Text(
          "暂无数据",
          style: FontUtil.fontGrey2(28, fontWeight: FontWeight.w500),
        ),
      );
    }
  }

  /// 内容显示方法
  Widget? _itemBuilder(BuildContext context, int index) {
    NoteChapterModel chapterModel = _list[index];
    return NoteExpandableWidget(
      chapterModel: chapterModel,
      columnType: widget.tabModel.type!,
      opening: index == 0,
    );
  }
}
